package cn.bonoon.handler.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import cn.bonoon.core.plugins.LoginRecordService;
import cn.bonoon.kernel.web.models.JsonResult;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <pre>
 * 登录失败时进入；
 * 如用户不存在、密码错误、该用户被禁止等登录失败的操作都交给这个类来处理
 * </pre>
 * @author jackson
 *
 */
public class AuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler {
	
	private final static String DEFAULT_LOGIN_FAILURE_URL = "/s/login/error";

	@Autowired
	private LoginRecordService loginRecordSevice;

	public AuthenticationFailureHandlerImpl() {
		super(DEFAULT_LOGIN_FAILURE_URL);
	}

	public AuthenticationFailureHandlerImpl(String defaultFailureUrl) {
		super(defaultFailureUrl);
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		
		if(isAjax(request)){
			ObjectMapper objectMapper = new ObjectMapper();
			response.setHeader("Content-Type", "application/json;charset=UTF-8");
			JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(), JsonEncoding.UTF8);
			try {
				// 失败为1
				String err = "登录名、密码或验证码不正确[" + exception.getMessage() + "]请重新输入！";
				JsonResult jsonData = JsonResult.error(err);
				objectMapper.writeValue(jsonGenerator, jsonData);
			} catch (JsonProcessingException ex) {
				throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
			}
			
			return ;
		}
		
//		@SuppressWarnings("deprecation")
//		Authentication authentication = exception.getAuthentication();
//		if(null != authentication){
//			try {
//				Object pri = authentication.getPrincipal();
//				String ip = RequestHelper.getIpAddress(request);
//				String id = request.getSession().getId();
//				if(pri instanceof LogonUser){
//					LogonUser bu = (LogonUser) pri;
//					loginRecordSevice.login(bu, exception.getMessage(), ip, false, id);
//				}else if(pri instanceof String){
//					String lname = (String)pri;
//					loginRecordSevice.login(lname, exception.getMessage(), ip, false, id);
//				}
//			} catch (Throwable err) {
//				// 忽略所有异常情况
//				err.printStackTrace();
//				logger.error("登录失败记录异常", err);
//			}
//			String name = authentication.getName();
//			logger.info(name + "用户登录失败了");
//		}
		super.onAuthenticationFailure(request, response, exception);
	}

	private boolean isAjax(HttpServletRequest request){ return false; }
}
